import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Channel } from '@/components/Channel'
import { useEffect, useRef, useState } from 'react'
import { Link, useHistory, useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { publishOrSaveArticle, getArticleById } from '@/store/actions'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'

const Publish = () => {
  const [form] = Form.useForm()
  const [fileList, setFileList] = useState([])
  const [maxCount, setMaxCount] = useState(1)
  const dispatch = useDispatch()
  const history = useHistory()
  const { id } = useParams()
  const fileListRef = useRef([])
  const isEdit = !!id
  useEffect(() => {
    const loadData = async () => {
      if (!isEdit) return

      const detail = await dispatch(getArticleById(id))
      const {
        title,
        channel_id,
        cover: { type, images },
        content,
      } = detail

      form.setFieldsValue({
        title,
        channel_id,
        type,
        content,
      })

      const newFileList = images.map((item) => ({
        url: item,
      }))

      setFileList(newFileList)

      setMaxCount(type)

      fileListRef.current = newFileList
    }
    loadData()
  }, [dispatch, id, isEdit, form])

  const publishOrSave = async (values, msg, isDraft) => {
    if (values.type !== fileList.length) {
      return message.warning('封面数量与所选类型不匹配')
    }
    const { type, ...rest } = values
    const data = {
      ...rest,
      cover: {
        type,
        images: fileList.map((item) => item.url),
      },
    }

    if (isEdit) {
      data.id = id
    }

    await dispatch(publishOrSaveArticle(data, isDraft, isEdit))
    message.success(msg, 1, () => {
      history.push('/home/article')
    })
  }
  const saveDraft = async () => {
    try {
      const values = await form.validateFields()
      publishOrSave(values, '存入草稿成功', true)
    } catch (e) {
      console.log(e)
    }
  }
  const onFinish = async (values) => {
    try {
      publishOrSave(values, isEdit ? '编辑文章成功' : '发表文章成功', false)
    } catch (e) {
      console.log(e)
    }
  }
  const onChangeValue = (e) => {
    const count = e.target.value
    setMaxCount(e.target.value)

    if (count === 1) {
      const newFileList = fileListRef.current[0] ? [fileListRef.current[0]] : []
      setFileList(newFileList)
    } else if (count === 3) {
      setFileList(fileListRef.current)
    }
  }
  const onUploadChange = (info) => {
    console.log(info)
    const newFileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      return file
    })

    fileListRef.current = newFileList

    setFileList(newFileList)
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {isEdit ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400}></Channel>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={onChangeValue}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {maxCount !== 0 && (
              <Upload
                action="http://geek.itheima.net/v1_0/upload"
                name="image"
                fileList={fileList}
                maxCount={maxCount}
                multiple={maxCount === 3}
                onChange={onUploadChange}
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
